<template>
    <el-card>
        <template #header>
            <h3>药品选购</h3>
        </template>
        <!-- 搜索区域 -->
        <el-form inline class="search">
            <el-form-item label="药品搜索" style="width: 220px">
                <el-input v-model="params.searchString" @keyup.enter="searchmedication()"></el-input>
            </el-form-item>
            <el-form-item label="医疗机构" style="width: 250px">
                <el-autocomplete v-model="params.institution" value-key="name"
                    :fetch-suggestions="querySearchInstitution" clearable class="inline-input w-50" placeholder="选择医疗机构"
                    @select="handleSelectInstitution" @input="clearInstitution" />
            </el-form-item>
            <el-form-item label="是否为处方药">
                <el-select v-model="params.isOTC" placeholder="" style="width: 60px">
                    <el-option v-for="item in OTCOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="searchmedication()">搜索</el-button>
            </el-form-item>
        </el-form>
        <!-- 药品列表 -->
        <div class="medication-list">
            <div class="item" v-for="item in medication" :key="item.id">
                <div class="img">
                    <el-image v-if="item.medication_img" :src="item.medication_img" @click="showMedication(item)" />
                    <el-image v-else src="src\assets\imgs\暂无图片.png" class="medication-img" />
                    <span v-if="item.stock <= 10 && item.stock > 0" class="stock">库存仅剩：{{ item.stock }}</span>
                    <span v-else-if="item.stock == 0" class="stock">暂无库存</span>
                </div>
                <div class="info">
                    <div class="name">{{ item.name }}</div>
                    <div class="prices-count">
                        <span class="price">￥{{ item.price.toFixed(2) }}</span>
                        <el-input-number v-if="item.count > 0" class="count" v-model="item.count" :min="0"
                            @change="handleChange" size="default" />
                        <el-button v-else type="primary" @click="handleChange1(item)">＋</el-button>
                    </div>
                </div>
            </div>
        </div>
        <!-- 分页区域 -->
        <el-pagination v-if="params.total > 0" :current-page="params.currentPage" :page-size="params.pageSize"
            background layout="total, prev, pager, next" :total="params.total" @current-change="handleCurrentChange" />
    </el-card>
    <!-- 药品详情弹窗 -->
    <el-dialog v-model="showMedicationWindow" :width="dialogWidth" title="">
        <div class="medication-info">
            <el-descriptions class="margin-top" :column="1" border label-width="100px">
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">药品：</div>
                    </template>
                    {{ curMedication.name }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">适应症：</div>
                    </template>
                    {{ curMedication.indications }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">规格：</div>
                    </template>
                    {{ curMedication.specification }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">用法用量：</div>
                    </template>
                    {{ curMedication.dosage }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">注意事项：</div>
                    </template>
                    {{ curMedication.precautions }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">不良反应：</div>
                    </template>
                    {{ curMedication.adverse_effects }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">有效期：</div>
                    </template>
                    {{ curMedication.expiration_date }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">生产厂商：</div>
                    </template>
                    {{ curMedication.manufacturer }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">批准文号：</div>
                    </template>
                    {{ curMedication.approval_number }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">是否为处方药：</div>
                    </template>
                    {{ curMedication.is_otc ? '' : '非' }}OTC
                </el-descriptions-item>
            </el-descriptions>
        </div>
    </el-dialog>
    <!-- 选择处方弹窗 -->
    <el-dialog v-model="showPrescriptionWindow" :width="dialogWidth" title="选择处方">
        <div class="prescription-info">
            <el-descriptions class="margin-top" :column="1" border label-width="140px">
                <el-descriptions-item v-for="(prescriptionItem, index) in prescriptionList.data" :key="index">
                    <template #label>
                        <p class="cell-item">{{ prescriptionItem.makeDate.substring(0, 10) }}</p>
                        <p>{{ prescriptionItem.institution }}</p>
                    </template>
                    <div class="prescription-item" @click="addToCart(prescriptionItem, prescriptionList.datas[index])">
                        <span v-for="(prescription, presIndex) in prescriptionList.datas[index]" :key="prescription.id">
                            {{ prescription.name + ' * ' + prescription.count + ' ' + prescription.unit }}
                            <span v-if="presIndex < prescriptionList.datas[index].length - 1">,</span>
                        </span>
                    </div>
                </el-descriptions-item>
            </el-descriptions>
        </div>
    </el-dialog>
    <!-- 购物车 -->
    <el-card class="cart-detail" v-if="showCart">
        <template #header>
            <div class="cart-title">
                <h3>购物车</h3>
                <div class="clear" @click="clearCart()">
                    <img src="@\assets\imgs\清空购物车.png" alt="" class="clear-img">
                    <span class="clear-text">清空购物车</span>
                </div>
            </div>
        </template>
        <el-table :data="cart" class="cart-table">
            <el-table-column label="" width="125">
                <template #default="scope">
                    <el-image :src="scope.row.medication_img" class="cart-medication-img"></el-image>
                    <p v-text="scope.row.name"></p>
                </template>
            </el-table-column>
            <!-- <el-table-column label="" prop="name" align="center"></el-table-column> -->
            <el-table-column label="" prop="price" width="90" align="center">
                <template #default="scope">
                    <div class="prices">
                        <span>￥{{ scope.row.price.toFixed(2) }}</span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="" prop="count" width="120" align="center">
                <template #default="scope">
                    <div class="count-unit">
                        <el-input-number class="count-small" v-model="scope.row.count" :min="0"
                            @change="cardHandleChange" size="small">
                        </el-input-number>
                        <span>&nbsp;{{ scope.row.unit }}</span>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <template #footer>
            <div class="cart-footer">
                <el-button type="primary" @click="searchPrescription()">查询处方</el-button>
                <div>
                    <span class="total-price">
                        合计：
                        <span class="total-price-text">
                            ￥{{ totalPrice.toFixed(2) }}
                        </span>
                    </span>
                    <el-button type="primary" @click="pay()">去结算</el-button>
                </div>
            </div>
        </template>
    </el-card>
    <div class="cart-box">
        <img src="@/assets/imgs/药箱.png" alt="" class="cart" @click="showCart = !showCart">
        <div class="cart-count" v-if="(totalCount > 0)">{{ this.totalCount }}</div>
    </div>
</template>
<script>
import { healthInstitutionFindAPI } from '@/api/healthInstitution';
import { medicationFindAPI } from '@/api/medication';
import { ordersAddAPI, ordersStatusUpdateAPI } from '@/api/orders';
import { prescriptionFindByResidentIdAPI } from '@/api/prescription';
import { ElMessage } from 'element-plus';
export default {
    data() {
        return {
            params: {
                resident_id: JSON.parse(sessionStorage.getItem('user')).user_id,
                // 搜索关键词
                institution_id: '',
                searchString: '',
                isOTC: '',
                // 分页参数
                total: 0,
                currentPage: 1,
                pageSize: 10
            },
            emptyParams: {},
            institutionsDropdown: [],
            medication: [],
            cart: [],
            OTCOptions: [
                {
                    value: '',
                    label: '全部'
                },
                {
                    value: '0',
                    label: '否'
                },
                {
                    value: '1',
                    label: '是'
                }
            ],
            curMedication: {},
            showMedicationWindow: false,
            showPrescriptionWindow: false,
            prescriptionList: '',
            showCart: false,
            totalCount: 0,
            totalPrice: 0.00,
            orders: {
                residentId: JSON.parse(sessionStorage.getItem('user')).user_id,
                institutionId: '',
                medications: '',
                orderPrice: 0.00,
                isPay: 0
            },
            dialogWidth: '700px',
            prescriptionParam: { residentId: JSON.parse(sessionStorage.getItem('user')).user_id },
        }
    },
    methods: {
        handleCurrentChange(page) {
            this.params.currentPage = page;
            this.loadMedicationList();
        },
        searchmedication() {
            if (this.params.institution_id == '') {
                ElMessage.warning('请先选择机构');
                return;
            }
            this.handleCurrentChange(1);
        },
        loadMedicationList() {
            medicationFindAPI(this.params).then((resp) => {
                if (resp.data.code == 2000) {
                    this.medication = resp.data.datas;
                    this.params.total = resp.data.total;
                    // 遍历medication
                    for (let i = 0; i < this.medication.length; i++) {
                        // 如果该行cart.count > 0，则使count = cart.count
                        if (this.cart.some(item => item.id === this.medication[i].id)) {
                            this.medication[i].count = this.cart.find(item => item.id === this.medication[i].id).count;
                        } else {
                            this.medication[i].count = 0;
                        }
                    }

                } else {
                    ElMessage.error(resp.data.message);
                }
            })
        },
        loadInstitutions() {
            healthInstitutionFindAPI(this.emptyParams).then((resp) => {
                if (resp.data.code == 2000) {
                    this.institutionsDropdown = resp.data.datas;
                } else {
                    ElMessage.error(resp.data.message);
                }
            })
        },

        handleChange() {
            this.totalCount = this.cart.reduce((pre, cur) => {
                if (cur.count > cur.stock) {
                    ElMessage.error(cur.name + ' 库存不足，请重新选择数量');
                    cur.count = cur.stock;
                }
                return pre + cur.count;
            }, 0);
            this.totalPrice = this.cart.reduce((pre, cur) => {
                return pre + cur.price * cur.count;
            }, 0);
            // 更新 this.cart 数组
            this.cart = this.cart.map(item => {
                let medicationItem = this.medication.find(med => med.id === item.id);
                if (medicationItem) {
                    item.count = medicationItem.count;
                }
                return item;
            });
            if (Array.isArray(this.cart)) {
                this.cart = this.cart.concat(this.filteredMedication);
                // 相同id的只保留最后一次
                this.cart = this.cart.reduce((acc, cur) => {
                    const existingItem = acc.find(item => item.id === cur.id);
                    if (!existingItem) {
                        return acc.concat(cur);
                    }
                    return acc;
                }, []);
            } else {
                console.error('this.cart 不是数组:', this.cart);
            }

            // 如果cart.count = 0，从cart删除
            this.cart = this.cart.filter(item => item.count > 0);
            sessionStorage.setItem('cart', JSON.stringify(this.cart));
        },
        handleChange1(item) {
            if (item.count == 0) {
                item.count += 2;
                this.handleChange();
                item.count--;
                this.handleChange();
            }
        },
        cardHandleChange() {
            this.totalCount = this.cart.reduce((pre, cur) => {
                if (cur.count > cur.stock) {
                    ElMessage.error(cur.name + '库存不足，请重新选择数量');
                    cur.count = cur.stock;
                }
                return pre + cur.count;
            }, 0);
            this.totalPrice = this.cart.reduce((pre, cur) => {
                return pre + cur.price * cur.count;
            }, 0);
            // 更新 this.medication 数组
            this.medication = this.medication.map(item => {
                let cartItem = this.cart.find(med => med.id === item.id);
                if (cartItem) {
                    item.count = cartItem.count;
                }
                return item;
            });
            if (Array.isArray(this.cart)) {
                this.cart = this.cart.concat(this.filteredMedication);
                // 相同id的只保留最后一次
                this.cart = this.cart.reduce((acc, cur) => {
                    const existingItem = acc.find(item => item.id === cur.id);
                    if (!existingItem) {
                        return acc.concat(cur);
                    }
                    return acc;
                }, []);
            } else {
                console.error('this.cart 不是数组:', this.cart);
            }
            // 如果cart.count = 0，从cart删除
            this.cart = this.cart.filter(item => item.count > 0);
            sessionStorage.setItem('cart', JSON.stringify(this.cart));
        },
        pay() {
            // medications赋值为药品ID*药品数量,...,
            this.orders.medications = this.cart.map(item => {
                if (item.count > 0) {
                    return item.id + "*" + item.count;
                }
            }).filter(item => item != undefined).join(",");
            // 去掉开头和结尾的所有逗号
            if (this.orders.medications.startsWith(",")) {
                this.orders.medications = this.orders.medications.slice(1);
            }
            if (this.orders.medications.endsWith(",")) {
                this.orders.medications = this.orders.medications.slice(0, -1);
            }

            if (this.orders.medications == "" || this.orders.medications == undefined || this.orders.medications == null || this.orders.medications.length == 0) {
                ElMessage.warning("请选择要购买的药品");
                return;
            } else {
                this.orders.orderPrice = this.totalPrice;
                let institution = {};
                institution.id = this.params.institution_id;
                institution.name = this.params.institution;
                ordersAddAPI(this.orders).then((resp) => {
                    if (resp.data.code == 2000) {
                        if (window.innerWidth < 768) {
                            this.method = 'mobile';
                        } else {
                            this.method = 'pc';
                        }
                        window.open(
                            "http://127.0.0.1:8081/alipay/pay?subject=" +
                            "药品" +
                            "&traceNo=" +
                            resp.data.data.id +
                            "&orderPrice=" +
                            this.totalPrice +
                            "&method=" +
                            this.method,
                            "_self"
                        );
                    } else {
                        ElMessage.error(resp.data.message);
                    }
                })
            }
        },
        showMedication(item) {
            this.showMedicationWindow = true;
            this.curMedication = item;
        },
        clearCart() {
            this.cart = [];
            this.totalCount = 0;
            this.totalPrice = 0;
            sessionStorage.setItem('cart', '[]');
            this.medication.forEach(item => {
                item.count = 0;
            });
        },
        //这是当输入数据时触发的，筛选出和输入数据匹配的建议输入。
        createFilter(queryString) {
            return (item) => {
                return item.name.toLowerCase().includes(queryString.toLowerCase());
            };
        },
        //该方法选择列表后触发
        handleSelectInstitution(item) {
            this.params.institution_id = item.id;
            this.orders.institutionId = item.id;
        },
        //输入框获取焦点时调用的方法
        querySearchInstitution(queryString, cb) {
            if (this.cart.length > 0) {
                ElMessage.warning("切换医疗机构请先清空购物车");
                return;
            }
            let results = this.institutionsDropdown;
            results = queryString
                ? results.filter(this.createFilter(queryString))
                : results;
            cb(results);
        },
        //点击清除按钮时触发事件
        clearInstitution() {
            this.params.institution_id = '';
            this.orders.institutionId = '';
        },
        setDialogWidth() {
            if (window.innerWidth < 768) {
                this.dialogWidth = '98vw';
            } else {
                this.dialogWidth = '700px';
            }
        },
        searchPrescription() {
            prescriptionFindByResidentIdAPI(this.prescriptionParam).then((resp) => {
                if (resp.data.code == 2000) {
                    this.prescriptionList = resp.data;
                    console.log(this.prescriptionList);

                    this.showPrescriptionWindow = true;
                } else {
                    ElMessage.error(resp.data.message);
                }
            })
        },
        addToCart(data, datas) {
            // 将data中的departmentId添加到datas的各个元素中
            datas.forEach(item => {
                item.institution_id = data.institutionId;
                item.medication_img = item.medicationImg;
            });
            // 修改cart的Session
            if (sessionStorage.getItem('cart') != null) {
                this.clearCart();
                if (Array.isArray(datas)) {
                    datas.forEach(item => {
                        const existingItem = this.cart.find(cartItem => cartItem.id === item.id);
                        if (!existingItem) {
                            this.cart.push(item);
                        }
                    });
                    sessionStorage.setItem('cart', JSON.stringify(this.cart));
                    // 计算药品数量和总价
                    this.totalCount = this.cart.reduce((acc, cur) => acc + cur.count, 0);
                    this.totalPrice = this.cart.reduce((acc, cur) => acc + cur.price * cur.count, 0);
                    this.orders.institutionId = data.institutionId;
                } else {
                    console.error('datas 不是数组:', datas);
                }
            }
            this.showPrescriptionWindow = false;
        }
    },
    computed: {
        // 为购物车过滤出count > 0的药品数据
        filteredMedication() {
            return this.medication.filter(item => item.count > 0);
        },
        filteredCart() {
            return this.cart.filter(item => item.count > 0);
        }

    },
    created() {
        this.loadInstitutions();
        // let institution = JSON.parse(localStorage.getItem('institution'));
        // if (institution != null) {
        //     this.params.institution_id = institution.id;
        //     this.params.institution = institution.name;
        //     this.loadMedicationList();
        // }
        if (sessionStorage.getItem('cart') == null) {
            sessionStorage.setItem('cart', '[]');
        }
        // 获取前一个页面的method
        let method = this.$route.query.method;
        let orders = {};
        orders.id = this.$route.query.out_trade_no;
        if (method && method.includes('alipay.trade.page.pay.return')) {
            // ordersStatusUpdateAPI(orders).then((resp) => {
            // if (resp.data.code == 2000) {
            ElMessage.success('支付成功');
            //     this.cart = [];
            // } else {
            //     ElMessage.error('支付失败');
            //     this.cart = JSON.parse(sessionStorage.getItem('cart'));
            // }
            // });
        }
        this.totalCount = this.cart.reduce((pre, cur) => {
            return pre + cur.count;
        }, 0);
        this.totalPrice = this.cart.reduce((pre, cur) => {
            return pre + cur.price * cur.count;
        }, 0);
    },
    mounted() {
        this.setDialogWidth();
        window.addEventListener('resize', this.setDialogWidth);
    },
    beforeDestroy() {
        window.removeEventListener('resize', this.setDialogWidth);
    }
}
</script>

<style scoped>
.example-pagination-block {
    display: flex;
    justify-content: center;
    align-items: center;
}

.el-pagination {
    margin-top: 20px;
    justify-content: center;
    align-items: center;
}

.el-card {
    width: 100%;
}

.description {
    margin: 0px 15px;
}

.medication-img {
    width: 100px;
    height: 100px;
}

.prices-count {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.count {
    width: 100px;
}

.medication-list {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
}

.medication-list .item {
    width: calc(20% - 20px);
    height: 100%;
    margin: 10px;
}

.medication-list .item .img {
    height: 100%;
    width: 100%;
    cursor: pointer;
    position: relative;
}

.medication-list .item .img .stock {
    position: absolute;
    right: 0px;
    bottom: 5px;
    width: 100%;
    height: 15%;
    background-color: rgb(255, 173, 51);
    opacity: 0.85;
    color: red;
    font-size: 20px;
    font-weight: bold;
    z-index: 999;
}


.medication-list .item .img .el-image {
    height: 100%;
    width: 100%;
}

.medication-list .item .info .price {
    font-size: 20px;
    color: #ff572d;
}

.medication-info .img {
    display: flex;
    justify-content: center;
    align-items: center;
}

.medication-info .img .medication-img {
    width: 300px;
    height: 300px;
}

.medication-info .is-bordered {
    padding: 0;
}

.cart-box {
    position: fixed;
    right: 30px;
    top: 140px;
    z-index: 999;
}

.cart-box .cart {
    width: 70px;
    cursor: pointer;
}

.cart-detail {
    position: fixed;
    right: 100px;
    top: 90px;
    z-index: 999;
    width: 400px;
}

.cart-detail .cart-table {
    max-height: 370px;
    /* 显示滚动条 */
    overflow: auto;
}

.cart-detail .cart-table .cart-medication-img {
    width: 100px;
}

.cart-detail .count-unit {
    display: flex;
}

.cart-detail .count-unit .count-small {
    width: 75px;
}

.cart-detail .cart-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.cart-detail .cart-title .clear {
    display: flex;
    align-items: center;
    cursor: pointer;
    color: #999;
    transition: all .2s;

    &:hover {
        color: #666;
    }
}

.cart-detail .cart-title .clear .clear-img {
    width: 20px;
}

.cart-detail .cart-title .clear .clear-text {
    font-size: 14px;
}

.cart-count {
    position: absolute;
    right: 0;
    top: 0;
    width: 20px;
    height: 20px;
    background-color: red;
    border-radius: 50%;
    color: #fff;
    text-align: center;
    font-weight: bold;
    line-height: 20px;
}

.cart-footer {
    line-height: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.total-price {
    margin-right: 10px;
}

.total-price .total-price-text {
    line-height: 20px;
    font-size: 20px;
    color: red;
}

.prescription-item {
    align-items: center;
    padding: 10px;
    cursor: pointer;
    transition: all .2s;

    &:hover {
        background-color: #eee;
    }
}

@media (max-width: 768px) {
    .search .el-form-item {
        width: 100% !important;
    }

    .medication-list .item {
        width: 48%;
        height: 100%;
        margin: 1%;
    }

    .cart-detail {
        right: 2vw;
        top: 30vh;
        width: 96vw;
    }

    .cart-detail .cart-table {
        max-height: 40vh;
    }
}
</style>